(function () {
    //一般直接写在一个js文件中
    layui.use(['layer', 'form', 'jquery'], function () {
        var layer = layui.layer
            , form = layui.form, $ = layui.jquery;
        //TODO 替换成可以配置的地址
        var basePath = 'http://localhost/';//http://192.168.1.110:8080/ssoServer/
        //var url = "ws://localhost:8080/ssoServer/websocket";
        var url = basePath.replace('http', 'ws') + "websocket";

        var ws = new WebSocket(url);

        ws.addEventListener('open', function (ev) {
            console.log('websocket已经连接建立链接');
            ws.send('Hello');
        });

        ws.onmessage = function (evt) {
            console.log("Received Message: " + evt.data);
            //{"code":10001,"msg":"登录成功","data":true}
            var json = evt.data;
            var hasCode = json.match("code");
            if (hasCode == null) {
                return;
            }
            var dataObj = eval("(" + json + ")");
            var code = dataObj.code;
            console.log("code=" + code);

            if (code == "10000") {
                //document.getElementById("loginQrImg").src="auth/getQrCodeImg?wsSessionId="+;
                $("#loginQrImg").attr("src",
                    "getQrCodeImg?wsSessionId=" + dataObj.data);
            } else if (code == "10001") {
                ws.close();
                reload();
            }
        };

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        };


        //关闭WebSocket连接
        function closeWebSocket() {
            ws.close();
        }

        //连接发生错误的回调方法
        ws.onerror = function () {

        };

        //刷新界面
        function reload() {
            window.location.reload();
        }
    });
})();